package commands

import (
	"bitwormhole.com/starter/cli"
	"bitwormhole.com/starter/cli/arguments"
	"github.com/bitwormhole/starter/markup"
	"github.com/bitwormhole/starter/vlog"
	"github.com/go-git/go-git/v5"
)

// GitAdd ...
type GitAdd struct {
	markup.Component `class:"cli-handler-registry"`
}

func (inst *GitAdd) _Impl() cli.HandlerRegistry {
	return inst
}

// GetHandlers ...
func (inst *GitAdd) GetHandlers() []*cli.HandlerRegistration {
	hr := &cli.HandlerRegistration{
		Name:    "go-git-add",
		Handler: inst.handle,
		Help:    nil,
		OnInit:  nil,
	}
	return []*cli.HandlerRegistration{hr}
}

func (inst *GitAdd) handle(t *cli.Task) error {

	atb := arguments.NewTemplateBuilder()
	args := atb.Create().Parse(t.Arguments)

	path := args.GetItem(0).String()
	wd := t.WD

	return inst.add(wd, path)
}

func (inst *GitAdd) add(wd string, path string) error {

	opt := &git.PlainOpenOptions{DetectDotGit: true}

	r, err := git.PlainOpenWithOptions(wd, opt)
	if err != nil {
		return err
	}

	wkt, err := r.Worktree()
	if err != nil {
		return err
	}

	id, err := wkt.Add(path)
	if err != nil {
		return err
	}

	vlog.Info("git.add.result:", id.String())
	return nil
}
